// src/pages/GradedDoctor/DoctorList.jsx

import React, { useState, useEffect } from 'react';
import { 
  Input, 
  Button, 
  Table, 
  Form, 
  Avatar,
  ConfigProvider,
  message
} from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import { searchDoctors } from '../../../request/wgqApi'; // 确保路径正确

// 样式定义
const Container = styled.div`
  padding: 24px;
  background: #fff;
  min-height: 100vh;
`;

const SearchForm = styled(Form)`
  margin-bottom: 24px;
  .ant-form-item {
    margin-bottom: 0;
    margin-right: 24px;
  }
`;

const StyledTable = styled(Table)`
  .ant-table-thead > tr > th {
    background: #fafafa;
    font-weight: 500;
  }
  
  .ant-table-tbody > tr > td {
    padding: 16px;
  }

  .ant-table-cell {
    color: rgba(0, 0, 0, 0.85);
  }
`;

const DoctorList = () => {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]); // 存储医生数据
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 5,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条`,
    pageSizeOptions: ['5', '10', '15', '20'],
  });
  const [form] = Form.useForm(); // 表单实例

  // 辅助函数：构建头像 URL
  const getAvatarSrc = (head) => {
    if (!head) return '/images/default-avatar.png'; // 使用默认头像
    if (head.startsWith('http://') || head.startsWith('https://')) {
      return head; // 直接使用完整的URL
    }
    return `http://localhost:21001/images/headers/${head}`; // 拼接完整的URL
  };

  // 表格列配置
  const columns = [
    {
      title: '医生姓名',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '所属科室',
      dataIndex: 'department',
      key: 'department',
      width: 200,
    },
    {
      title: '医生头像',
      dataIndex: 'head', // 修改为 'head' 对应 API 返回的头像字段
      key: 'head',
      width: 200,
      render: (head) => (
        <Avatar 
          src={getAvatarSrc(head)}
          size={64}
          style={{ backgroundColor: '#f0f0f0' }}
        />
      ),
    },
    {
      title: '联系方式',
      dataIndex: 'phone',
      key: 'phone',
      width: 200,
    },
    {
      title: '性别',
      dataIndex: 'sex', // 修改为 'sex' 对应 API 返回的性别字段
      key: 'sex',
      width: 100,
    },
  ];

  // 获取医生数据
  const fetchDoctors = async (params = {}) => {
    setLoading(true);
    try {
      const response = await searchDoctors(params);
      if (response.code === 1) { // 根据API响应修改判断条件
        // 为每个数据项添加 'key' 属性
        const dataWithKey = response.data.map(item => ({
          ...item,
          key: item.id, // 使用 'id' 作为唯一键
        }));
        setData(dataWithKey); // 假设返回的数据结构为 { code: 1, data: { items: [], total: number } }
        setPagination({
          ...pagination,
          current: params.page || 1,
          pageSize: params.size || 16,
          total: response.total,
        });
      } else {
        message.error(response.msg || '获取医生数据失败');
      }
    } catch (error) {
      message.error('获取医生数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 初次加载数据
  useEffect(() => {
    fetchDoctors({
      page: pagination.current,
      size: pagination.pageSize,
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 表格分页处理
  const handleTableChange = (newPagination, filters, sorter) => {
    fetchDoctors({
      page: newPagination.current,
      size: newPagination.pageSize,
      ...form.getFieldsValue(),
    });
  };

  // 搜索处理
  const handleSearch = (values) => {
    fetchDoctors({
      page: 1, // 重置到第一页
      size: pagination.pageSize,
      name: values.doctorName || '',
      department: values.department || '',
    });
  };

  return (
    <ConfigProvider
      theme={{
        components: {
          Table: {
            headerBg: '#fafafa',
            headerColor: 'rgba(0, 0, 0, 0.85)',
            rowHoverBg: '#f5f5f5',
            borderColor: '#f0f0f0',
          },
        },
      }}
    >
      <Container>
        {/* 搜索表单 */}
        <SearchForm
          form={form}
          layout="inline"
          onFinish={handleSearch}
        >
          <Form.Item name="doctorName"  label="医生姓名">
            <Input
              placeholder="请输入医生姓名"
              style={{ width: 200 }}
              allowClear
            />
          </Form.Item>
          <Form.Item name="department"  label="医生科室">
            <Input
              placeholder="请输入科室"
              style={{ width: 200 }}
              allowClear
            />
          </Form.Item>
          <Form.Item>
            <Button 
              type="primary" 
              icon={<SearchOutlined />}
              htmlType="submit"
            >
              查询
            </Button>
          </Form.Item>
        </SearchForm>

        {/* 表格 */}
        <StyledTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          onChange={handleTableChange}
          loading={loading}
          bordered
          size="middle"
          scroll={{ x: 'max-content' }}
          rowClassName={(record, index) => 
            index % 2 === 0 ? 'table-row-light' : 'table-row-dark'
          }
        />
      </Container>
    </ConfigProvider>
  );
};

// 全局样式
const GlobalStyle = styled.div`
  .table-row-light {
    background-color: #fff;
  }
  
  .table-row-dark {
    background-color: #fafafa;
  }

  .ant-input {
    border-radius: 4px;
  }

  .ant-btn {
    border-radius: 4px;
  }

  .ant-pagination-options {
    .ant-select-selector {
      border-radius: 4px;
    }
  }
`;

export default () => (
  <GlobalStyle>
    <DoctorList />
  </GlobalStyle>
);